package service

import (
	"d-blog/dao"
	"d-blog/db"
	"d-blog/model"
	"d-blog/pkg/query"
	"encoding/json"
	"fmt"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
	"net/url"
)

type tipService struct {
}

var TipService = newTipService()

func newTipService() *tipService {
	return &tipService{}
}

func (receiver *tipService) GetById(id string) model.Tip {
	return dao.SinaTipDao.GetById(db.DB(), id)
}

func (receiver *tipService) GetList() {

}

// CollectData 采集新浪微博的数据
func (receiver *tipService) CollectData(sinaOauth2Token string) {
	fmt.Println("正在采集数据")
	weiboUrl := "http://wthrcdn.etouch.cn/weather_mini"
	//校验url
	parsedUrl, err2 := url.Parse(weiboUrl)
	if nil != err2 {
		log.Errorf("请求路径解析失败：url=%s", weiboUrl)
		return
	}
	queryParams := url.Values{}
	queryParams.Add("access_token", sinaOauth2Token)
	queryParams.Add("count", "500")
	queryParams.Add("filter_by_type", "1")

	parsedUrl.RawQuery = queryParams.Encode()
	log.Infof("最终的查询URL=%s", parsedUrl.String())

	resp, err := http.Get(weiboUrl)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	fmt.Println(string(body))
	fmt.Println(resp.StatusCode)

	var result = model.SinaTipRecord{}
	if resp.StatusCode == 200 {
		if nil != json.Unmarshal(body, &result) {
			log.Fatalln("采集微博数据失败")
		}
		// 开始处理数据
		fmt.Printf("%#v", result)
	} else {
		log.Fatalln("调用采集接口失败")
	}
}

func (receiver *tipService) DownloadSinaImages() {
	//从mysql查询图片信息
	find := dao.SinaTipDao.Find(db.DB(), query.NewCondition().Where("id", "4294053921503673"))
	fmt.Println(find)
	//从远程下载图片

}
func (receiver *tipService) CountFib(n int) (fibN int) {
	fibN = fib(n)
	fmt.Printf("\rFibonacci(%d) = %d\n", n, fibN)
	return fibN
}

//计算斐波拉契数列 x 为第多少位
func fib(x int) int {
	if x < 2 {
		return x
	}
	return fib(x-1) + fib(x-2)
}
